<?php
// $Id: popnupblog.php,v 2.10.3 2005/07/16 21:37:00 yoshis Exp $
if(
	!defined('XOOPS_ROOT_PATH') || 
	!is_file(XOOPS_ROOT_PATH.'/modules/popnupblog/conf.php') ||
	!is_file(XOOPS_ROOT_PATH.'/class/snoopy.php') ||
	!is_file(XOOPS_ROOT_PATH.'/modules/popnupblog/PopnupBlogUtils.php')
){
	exit();
}
require_once XOOPS_ROOT_PATH.'/modules/popnupblog/conf.php';
require_once XOOPS_ROOT_PATH.'/class/snoopy.php';
require_once XOOPS_ROOT_PATH.'/modules/popnupblog/PopnupBlogUtils.php';
require_once XOOPS_ROOT_PATH.'/modules/popnupblog/get_mailcode.php';

class PopnupBlog {
	var $VIEW_NUM = 20;
	
	var $user_list;
	var $blogid;
	var $blogUid;
	var $blogGid;
	var $targetUser;
	var $userHander;
	var $permission = -1;
	var $title = '';
	var $blog_desc = '';
	var $usersCache = array();
	var $ts;
	var $xoopsDB;
	var $popnupblog_configs = array();
	
	function PopnupBlog($blogid = -1){
		global $xoopsUser, $xoopsDB;

		$this->xoopsDB =& $xoopsDB;
		$this->userHander = new XoopsUserHandler($this->xoopsDB);
		$this->ts =& MyTextSanitizer::getInstance();
		$this->user_list = array();
		if(!$this->blogUid) $this->loadBlogInfo($blogid);
		if($this->blogUid > 0){
			$this->targetUser = $this->userHander->get($this->blogUid);
			if ($xoopsUser && $xoopsUser->isAdmin()) return;
			$admin = 0;
			if (!empty($xoopsUser)) $admin = $xoopsUser->isAdmin();
			if( !$admin && (!$this->targetUser) || (!$this->targetUser->isActive())){
				redirect_header(POPNUPBLOG_DIR,2,_MD_POPNUPBLOG_NORIGHTTOACCESS);
				exit();
			}
			$usersCache[$this->blogUid] = $this->targetUser;
		}else{
			redirect_header(XOOPS_URL.'/',5,_MD_POPNUPBLOG_INTERNALERROR.' NoMatch blogid('.$blogid.')');
			exit();
		}
	}
	
	
	
	function getAllApplication(){
		global $xoopsDB;
		if(!$qResult = $xoopsDB->query('select uid, groupid, cat_id, title, blog_desc, permission, UNIX_TIMESTAMP(create_date), email, emailalias from '.POPNUPBLOG_TABLE_APPL.' order by create_date' )){
			return false;
		}
		$result = array();
		while(list($uid, $groupid, $cat_id, $title, $desc, $permission, $create_date, $email, $emailalias) = $xoopsDB->fetchRow($qResult)){
			$result[] = array(
				'uid' => $uid, 
				'gid' => $groupid, 
				'cat_id' => $cat_id, 
				'title' => $title, 
				'desc' => $desc, 
				'permission' => $permission, 
				'create_date' => $create_date,
				'email' => $email, 
				'emailalias' => $emailalias 
				);
		}
		return $result;
	}
	function getTargetUname(){
		return $this->getUname($this->blogUid);
//		return $this->targetUser->uname();
	}
	
	function setBlogInfo( $gid=0, $cat_id=0, $permisstion = 0, $title = "", $desc = "", $email = ''){
		$title = htmlspecialchars($title);
		$this->xoopsDB->queryF('update '.POPNUPBLOG_TABLE_INFO.' set groupid='.intval($gid).',cat_id='.intval($cat_id).',blog_permission='.intval($permisstion).
		',title=\''.PopnupBlogUtils::convert2sqlString($title).'\',blog_desc=\''.PopnupBlogUtils::convert2sqlString($desc).'\',email=\''.$email.'\' where blogid='.$this->blogid);
	}
	
	function deleteAll(){
		$this->xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_INFO.' where blogid = '.$this->blogid);
		$this->xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_BLOG.' where blogid = '.$this->blogid);
		$this->xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_COMMENT.' where blogid = '.$this->blogid);
		$this->xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_TRACKBACK.' where blogid = '.$this->blogid);
		//  Modified by hoshiyan@hoshiba-farm.com 2004.8.5
		$this->xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' where blogid = '.$this->blogid);
	}
	
	function loadBlogInfo( $blogid = 0 ){
		global $xoopsUser;

		if ($blogid==0) $blogid=$this->blogid;
		$sql = 'select uid,blogid,groupid, blog_permission, title, blog_desc from '.POPNUPBLOG_TABLE_INFO.' where blogid='.$blogid;
		if(!$result = $this->xoopsDB->query($sql)){
			return false;
		}
		if(list($uid,$blogid,$gid, $permission, $title, $desc) = $this->xoopsDB->fetchRow($result)){
			$this->blogUid = $uid;
			$this->blogid = $blogid;
			$this->blogGid = $gid;
			$this->permission = $permission;
			$this->title = $title;	//$this->ts->makeTareaData4Edit();
			$this->blog_desc = $desc;	//$this->ts->makeTareaData4Edit();
			return true;
		}
		return false;
	}
	
	
	function canWrite($blogid=0){
		global $xoopsUser;
		
		if(!$xoopsUser) return false;
		if ($this->permission < 0) {
			if(!$this->loadBlogInfo($blogid)){
				return false;
			}
		}
		if($xoopsUser->uid() == $this->blogUid) return true;
		$member_handler =& xoops_gethandler('member');
		$my_group_ids =& $member_handler->getGroupsByUser( $this->targetUser->uid() ) ;
		//echo $this->blogGid; print_r( $my_group_ids);
		foreach ($my_group_ids as $gid){
			if($gid==$this->blogGid){ return true; }
		}
		return false;	
	}
	
	function canRead($blogid=0){
		global $xoopsUser;
		
		if($xoopsUser){
			if ( $xoopsUser->uid() == $this->blogUid ) return true;
		}
		if($this->permission < 0) $this->loadBlogInfo($blogid);
		$canread = ($this->permission & 0x07);
		switch ($canread){
			case 0x07: if (!$xoopsUser) $ret = false; else if ( $this->isPrivate($blogid) ) $ret=true; break;
			case 0x06: if (!$xoopsUser) $ret = false; else if ( $xoopsUser->getVar('rank')>=6 ) $ret=true; break;
			case 0x01: if (!$xoopsUser) $ret = false; else if ( $xoopsUser ) $ret=true; break;
			case 0x00: $ret=true; break;
		}
		return $ret;
	}
	
	function canComment($blogid=0){
		global $xoopsUser;
		
		if($this->permission < 0) $this->loadBlogInfo($blogid);
		$cancomment = ($this->permission & 0x38)>>3;
		switch ($cancomment){
			case 0x07: if (!$xoopsUser) $ret = false; else if ( $xoopsUser->isAdmin() ) $ret=true; break;
			case 0x06: if (!$xoopsUser) $ret = false; else if ( $xoopsUser->getVar('rank')>=6 ) $ret=true; break;
			case 0x01: if (!$xoopsUser) $ret = false; else if ( $xoopsUser ) $ret=true; break;
			case 0x00: $ret=true; break;
		}
		return $ret;
	}
	function canVote($blogid=0){
		global $xoopsUser;
		
		if($this->permission < 0) $this->loadBlogInfo($blogid);
		$canvote = ($this->permission & 0x1c0)>>6;
		switch ($canvote){
			case 0x07: if (!$xoopsUser) $ret = false; else if ( $xoopsUser->isAdmin() ) $ret=true; break;
			case 0x06: if (!$xoopsUser) $ret = false; else if ( $xoopsUser->getVar('rank')>=6 ) $ret=true; break;
			case 0x01: if (!$xoopsUser) $ret = false; else if ( $xoopsUser ) $ret=true; break;
			case 0x00: $ret=true; break;
		}
		return $ret;
	}
	function isPrivate($blogid=0){
		global $xoopsUser;
		if (!$xoopsUser) return false;
		if ( $xoopsUser->isAdmin() )  return true;
		$sql = 'select count(*) from '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' where blogid = '.$blogid.' and uid='. $xoopsUser->uid();
		if(list($num) = $this->xoopsDB->fetchRow($this->xoopsDB->query($sql))){
			return true;
		}
	}
	function isPublic(){
		if($this->permission < 0){
			$this->loadBlogInfo();
		}
		
		$canread = $this->permission & 0x07;
		if( $this->permission < 7 ){	// admin = not public
			return true;
		}
		return false;
	}
	
	function useTrackBack(){
		if(!array_key_exists('POPNUPBLOG_TRACKBACK', $this->popnupblog_configs)){
			$tb = PopnupBlogUtils::getXoopsModuleConfig('POPNUPBLOG_TRACKBACK');
			$this->popnupblog_configs['POPNUPBLOG_TRACKBACK'] = ($tb == 1) ? true : false;
		}
		return $this->popnupblog_configs['POPNUPBLOG_TRACKBACK'];
	}
	
	function useUpdatePing(){
		if(!array_key_exists('POPNUPBLOG_UPDATE_PING', $this->popnupblog_configs)){
			$conf = PopnupBlogUtils::getXoopsModuleConfig('POPNUPBLOG_UPDATE_PING');
			$this->popnupblog_configs['POPNUPBLOG_UPDATE_PING'] = ($conf == 1) ? true : false;
		}
		return $this->popnupblog_configs['POPNUPBLOG_UPDATE_PING'];
	}
	
	function getTitle(){
		if($this->permission < 0){
			$this->loadBlogInfo();
		}
		if($this->title != ''){
			return $this->title;
		}else{
			return _MD_POPNUPBLOG_TITLE_PREFIX.$this->getTargetUname()._MD_POPNUPBLOG_TITLE_SUFFIX;
		}
	}
	function getBlogdesc(){
		if($this->permission < 0){
			$this->loadBlogInfo();
		}
		if($this->blog_desc != ''){
			return $this->ts->makeTareaData4Show($this->blog_desc);
		}else{
			return null;
		}
	}
	
	function getBlogData($year = 0, $month = 0, $date = 0, $hours=0, $minutes=0, $seconds=0, $command=0, $limit=0,$voteorder=0){
		global $xoopsConfig,$xoopsUser,$weekday,$d_month;
		$debug = 0;

		if($limit == 0){
			$limit = POPNUPBLOG_VIEW_LIST_NUM;
		}
		$dateFormat = '%y/%m/%d';
		if(!$this->canRead($this->blogid)){
			redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_NORIGHTTOACCESS);
			exit();
		}
		$addorder = '';
		if ($voteorder==1) $addorder = " votes_yes desc,";
		$sql_blog = '';
		$sql_select = 'select uid, UNIX_TIMESTAMP(last_update) last_update, blog_date, title, post_text, votes_yes, votes_no from ';
		$tb = $this->useTrackBack();
		if($this->blogid)
			$blogw = ' where blogid = '.$this->blogid;
		$sql_where = '';
		if( ($year > 1000) && ($month > 0) ){
			if($date > 0){
				if($hours > 0){	// display one blog
					if ( $xoopsUser ) { 
						$userTZ = $xoopsUser->getVar("timezone_offset");
					} else { 
						$userTZ = $xoopsConfig['default_TZ'];
					}
					$user_time = strtotime($year.'-'.$month.'-'.$date.' '.$hours.':'.$minutes.':'.$seconds);
					$server_time = userTimeToServerTime($user_time,$userTZ);
					$year    = strftime("%Y", $server_time);
					$month   = strftime("%m", $server_time);
					$date    = strftime("%d", $server_time);
					$hours   = strftime("%H", $server_time);
					$minutes = strftime("%M", $server_time);
					$seconds = strftime("%S", $server_time);
					$sql_where = $blogw.' and blog_date= \''.$year.'-'.$month.'-'.$date.' '.$hours.':'.$minutes.':'.$seconds.'\' order by'.$addorder.' blog_date desc ';
				} else { // display date blog
					$sql_where = $blogw.' and DATE_FORMAT(blog_date, \'%Y\')='.$year.' and DATE_FORMAT(blog_date, \'%m\') = '.$month.' and DATE_FORMAT(blog_date, \'%d\') = '.$date.' order by'.$addorder.' blog_date desc limit '.$limit;
				}
			}else{ // display month blog
				$sql_where = $blogw.' and DATE_FORMAT(blog_date, \'%Y\')='.$year.' and DATE_FORMAT(blog_date, \'%m\') = '.$month.' order by'.$addorder.' blog_date desc limit '.$limit;
				$tb = false;
			}
		}
		if($sql_where == ''){ // display current blog
			$sql_where = $blogw.' order by'.$addorder.' blog_date desc limit '.$limit;
			$tb = false;
		}
		$sql_blog = $sql_select.POPNUPBLOG_TABLE_BLOG.$sql_where;
		if ($debug) {
			echo $sql_blog."\n<br>";
		}
		if(!$result_blog = $this->xoopsDB->query($sql_blog)){
			return false;
		}
		$result = array();
		$i = 0;
		$cDate=0;
		while(list($uid,$last_update,$result_date, $result_title,$result_post_text,$votes_yes,$votes_no)
			= $this->xoopsDB->fetchRow($result_blog)){
			$poster = new XoopsUser( $uid ) ;
			$result['blog'][$i]['uid']  = $uid;
			$result['blog'][$i]['uname'] = $this->getUname($uid);
			//$result['blog'][$i]['uname'] = $this->uname($uid);
			//
			// modified by hoshiyan@hoshiba-farm.com 2004.07.15
			//
			$server_time = strtotime($result_date);
			$user_time = xoops_getUserTimestamp($server_time);
			if ($debug) {
				echo $result_title;
				echo $result_date;
				echo 'ServerTime = '.$server_time.'UserTime = '.$user_time;
			}
			$result['blog'][$i]['year']  = strftime("%Y", $user_time);
			$result['blog'][$i]['month'] = strftime("%m", $user_time);
			$result['blog'][$i]['date']  = strftime("%d", $user_time);
			setlocale(LC_ALL,'ja-JP');
			// Make a Date strings 2004.9.9 Yoshi.Sakai
			if (_MD_CAL_FORMAT=="Y-M-D"){		// ISO-8601
				$result['blog'][$i]['date_str']  =
					strftime("%Y", $user_time)._MD_CAL_PERMIT_Y.
					$d_month[date('m', $user_time)]._MD_CAL_PERMIT_M.
					strftime("%d", $user_time)._MD_CAL_PERMIT_D.
					"(".$weekday[date('w', $user_time)].")";
			} elseif(_MD_CAL_FORMAT=="M-D-Y") {	// US
				$result['blog'][$i]['date_str']  =
					$d_month[date('m', $user_time)]._MD_CAL_PERMIT_M.
					strftime("%d", $user_time)._MD_CAL_PERMIT_D.
					"(".$weekday[date('w', $user_time)].")"._MD_CAL_PERMIT_Y.
					strftime("%Y", $user_time);
			} elseif(_MD_CAL_FORMAT=="D-M-Y") {	// Other
				$result['blog'][$i]['date_str']  =
					strftime("%d", $user_time)._MD_CAL_PERMIT_D.
					$d_month[date('m', $user_time)]._MD_CAL_PERMIT_M.
					"(".$weekday[date('w', $user_time)].")"._MD_CAL_PERMIT_Y.
					strftime("%Y", $user_time);
			}else{
				strftime("%Y", $user_time)."/".
				strftime("%m", $user_time)."/".
				strftime("%d", $user_time);
			}
			if ($cDate!=strftime("%d", $user_time)){
				$result['blog'][$i]['hidedate']  = false;
				$cDate = $result['blog'][$i]['date'];
			}else{
				$result['blog'][$i]['hidedate']  = true;
			}
			$result['blog'][$i]['hours']  = strftime("%H", $user_time);
			$result['blog'][$i]['minutes']  = strftime("%M", $user_time);
			$result['blog'][$i]['seconds']  = strftime("%S", $user_time);
			$result['blog'][$i]['date_all'] = formatTimestamp($server_time, 'mysql');
			$result['blog'][$i]['title'] = $result_title;
			$result_post_text =& str_replace(":download:", "<img src=./images/attachment.gif alt='' />",$result_post_text);
			$result['blog'][$i]['text'] = $this->ts->makeTareaData4Show(PopnupBlogUtils::phpbbsmiley($result_post_text));
			$result['blog'][$i]['text_edit'] = $this->ts->makeTareaData4Edit($result_post_text);
			$result['blog'][$i]['comments'] = $this->getComments($result_date);
			$result['blog'][$i]['url'] = PopnupBlogUtils::createUrl($this->blogid, $result['blog'][$i]['year'], $result['blog'][$i]['month'], $result['blog'][$i]['date'], $result['blog'][$i]['hours'], $result['blog'][$i]['minutes'], $result['blog'][$i]['seconds']);
			$result['blog'][$i]['last_update_s'] = formatTimestamp($last_update, 's');
			$result['blog'][$i]['last_update_m'] = formatTimestamp($last_update, 'm');
			$result['blog'][$i]['last_update_l'] = formatTimestamp($last_update, 'l');
			$result['blog'][$i]['last_update4rss'] = PopnupBlogUtils::toRssDate($last_update);
			$votes_all = $votes_yes + $votes_no;
			$result['blog'][$i]['votes_yes'] = $votes_yes;
			$result['blog'][$i]['votes_no']  = $votes_no;
			$result['blog'][$i]['votes_all'] = $votes_all;
			$result['blog'][$i]['votes_yes_par'] = $votes_yes ? ($votes_yes/$votes_all*100) : 0;
			$result['blog'][$i]['votes_no_par']  = $votes_no  ? ($votes_no/$votes_all*100)  : 0;
			$result['blog'][$i]['votes_yes_pix'] = $votes_yes ? ($votes_yes/$votes_all*100)*2 : 0;
			$result['blog'][$i]['votes_no_pix']  = $votes_no  ? ($votes_no/$votes_all*100)*2  : 0;
			if($tb == true){
				$result['blog'][$i]['trackback_url'] = PopnupBlogUtils::createUrl($this->blogid, $result['blog'][$i]['year'], $result['blog'][$i]['month'], $result['blog'][$i]['date'], $result['blog'][$i]['hours'], $result['blog'][$i]['minutes'], $result['blog'][$i]['seconds'], 'tb');
			}
			$result['blog'][$i]['trackbacks'] = $this->getTrackBack($result['blog'][$i]);
			$result['blog'][$i]['tb_count'] = count($result['blog'][$i]['trackbacks']);
			$i++;
		}
		$result['jump_url'] = $this->mk_jump_url($year,$month,$date);
		$result['blog_num'] = $i;
		$user_time = xoops_getUserTimestamp(time());			//  $time = time();
		$result['today']['year'] = strftime("%Y", $user_time);          // date('Y',$time);
		$result['today']['month'] = strftime("%m", $user_time);         // date('m',$time);
		$result['today']['date'] = strftime("%d", $user_time);          // date('d',$time);
		$result['today']['hours'] = strftime("%H", $user_time);         // date('H',$time);
		$result['today']['minutes'] = strftime("%M", $user_time);       // date('i',$time);
		$result['today']['seconds'] = strftime("%S", $user_time);       // date('s',$time);
/*
		$time = time();
		$result['today']['year'] = date('Y',$time);
		$result['today']['month'] = date('m',$time);
		$result['today']['date'] = date('d',$time);
		$result['today']['hours'] = date('H',$time);
		$result['today']['minutes'] = date('i',$time);
		$result['today']['seconds'] = date('s',$time);
*/
		$result['user'] = $this->targetUser;
		$result['uid'] = $this->blogUid;
		$result['uname'] = $this->getUname($this->blogUid);	//$this->targetUser->uname();
		
		if ($debug) {
			echo 'Today = '.$user_time;
			print_r($result);
		}
		return $result;
	}
	
	function mk_jump_url($year = 0, $month = 0, $date = 0){
		global $start;
		$sql_where = ' where blogid = '.$this->blogid;
		if( ($year > 1000) && ($month > 0) ){
			if($date > 0){
				$sql_where = $sql_where.' and DATE_FORMAT(blog_date, \'%Y\')='.$year.' and DATE_FORMAT(blog_date, \'%m\') = '.$month.' and DATE_FORMAT(blog_date, \'%d\') = '.$date;
			}else{ // display month blog
				$sql_where = $sql_where.' and DATE_FORMAT(blog_date, \'%Y\')='.$year.' and DATE_FORMAT(blog_date, \'%m\') = '.$month;
			}
		}
		$n = 1;
		$urls = '';
		$nurl = '';
		$cflg = false;
		$sql = "select count(*) from ".POPNUPBLOG_TABLE_BLOG.$sql_where;
		if(list($num) = $this->xoopsDB->fetchRow($this->xoopsDB->query($sql))){
			for ($i=0;$i<$num;$i+=POPNUPBLOG_VIEW_LIST_NUM){
				$cstart=$i.",".POPNUPBLOG_VIEW_LIST_NUM;
				if ($start==$cstart){
					$nstr='('.$n.')';
					$cflg=true;
				} else {
					if ($cflg==true)
						$nurl='<a href="'.PopnupBlogUtils::createUrl($this->blogid,$year,$month,$date).'&start='.$cstart.'"><u>&raquo</u></a>&nbsp';
					$nstr=$n;
					$cflg=false;
				}
				$urls = $urls.'<a href="'.PopnupBlogUtils::createUrl($this->blogid,$year,$month,$date).'&start='.$cstart.'">'.$nstr.'</a>&nbsp';
				$n++;
			}
			$urls = $urls.$nurl;
		}
//		echo $urls;
		return $urls;
	}
	
	/*
	function hasBlog($dates){
		$sqlDate = $this->xoopsDB->quoteString($dates['year'].'-'.$dates['month'].'-'.$dates['date']);
		$sql = "select count(*) from ".POPNUPBLOG_TABLE_BLOG." where uid = ".$this->blogUid.' and  blog_date = '.$sqlDate;
		if(!$result_select = $this->xoopsDB->query($sql)){
			if(list($num) = $this->xoopsDB->fetchRow($result_select)){
				if($num > 0){
					return true;
				}
			}
		}
		return false;
	}
	*/
	function getBlog1($dates,$blogid=''){
		global $xoopsUser;
		$debug = 0;
		$sqlDate = $dates['year'].'-'.$dates['month'].'-'.$dates['date'].' '.$dates['hours'].':'.$dates['minutes'].':'.$dates['seconds'];
		$sql = 'select title, post_text FROM '.POPNUPBLOG_TABLE_BLOG.' WHERE blogid = '.$blogid.' and  blog_date = \''.$sqlDate.'\'';
		if(!$result_select = $this->xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		//
		// modified by hoshiyan@hoshiba-farm.com 2004.07.15
		//
		$server_time = mktime($dates['hours'],$dates['minutes'],$dates['seconds'],$dates['month'],$dates['date'],$dates['year']);
		$user_time = xoops_getUserTimestamp($server_time);
		$result['year'] = strftime("%Y", $user_time);
		$result['month'] = strftime("%m", $user_time);
		$result['date'] = strftime("%d", $user_time);
		$result['hours'] = strftime("%H", $user_time);
		$result['minutes'] = strftime("%M", $user_time);
		$result['seconds'] = strftime("%S", $user_time);
		$usrDate =  formatTimestamp($server_time, 'mysql');
/*
		$result['year'] = $dates['year'];
		$result['month'] = $dates['month'];
		$result['date'] = $dates['date'];
		$result['hours'] = $dates['hours'];
		$result['minutes'] = $dates['minutes'];
		$result['seconds'] = $dates['seconds'];
*/			
		if(list($title, $text) = $this->xoopsDB->fetchRow($result_select)){
			$result['date_all'] = $usrDate;	//$result['date_all'] = $sqlDate;
			$result['title'] = $title;
			$result['text'] = $this->ts->makeTareaData4Show($text);
			$result['text_edit'] = $this->ts->makeTareaData4Edit($text);
		}
		if ($debug) {
			print_r($dates);
			echo $server_time;
			echo $user_time;
			print_r($result);
		}
		return $result;
	}
	
	function getComments($blogDate){
		global $xoopsUser;

		$vote_yes = $vote_no = $vote_all = 0;
		$debug=1;
		$sql = 'select comment_id, comment_uid,comment_name, post_text, create_date, vote from '.POPNUPBLOG_TABLE_COMMENT.' where blogid = '.$this->blogid.' and blog_date = '.$this->xoopsDB->quoteString($blogDate).' order by comment_id '; 
		if(!$result_select = $this->xoopsDB->query($sql)){
			return false;
		}
		$i = 0;
		$comments = array();
		if (!empty($xoopsUser)) $admin = $xoopsUser->isAdmin();
		$cDate = 0;
		while(
			list($comment_id, $comment_uid, $comment_name, $post_text, $create_date, $vote) = $this->xoopsDB->fetchRow($result_select)
		){
			$comments[$i]['id'] = $comment_id;
			$comments[$i]['uid'] = $comment_uid;

			$server_time = strtotime($create_date);
			$user_time = xoops_getUserTimestamp($server_time);
//			if ($debug) {
//				echo $create_date;
//				echo 'ServerTime = '.$server_time.'UserTime = '.$user_time;
//			}
			$result['blog'][$i]['year']  = strftime("%Y", $user_time);
			$result['blog'][$i]['month'] = strftime("%m", $user_time);
			$result['blog'][$i]['date']  = strftime("%d", $user_time);
			if ($cDate!=strftime("%d", $user_time)){
				$result['blog'][$i]['hidedate']  = false;
				$cDate = $result['blog'][$i]['date'];
			}else{
				$result['blog'][$i]['hidedate']  = true;
			}
			$result['blog'][$i]['hours']  = strftime("%H", $user_time);
			$result['blog'][$i]['minutes']  = strftime("%M", $user_time);
			$result['blog'][$i]['seconds']  = strftime("%S", $user_time);
			$result['blog'][$i]['date_all'] = formatTimestamp($server_time, 'mysql');
			$comments[$i]['create_date'] = $create_date;
			$comments[$i]['create_date_s'] = ($create_date == 0) ? '<unknown>' : strftime("%m/%d", $user_time);
			$comments[$i]['create_date_m'] = ($create_date == 0) ? '<unknown>' : strftime("%m/%d %H:%M", $user_time);
			$comments[$i]['create_date_l'] = ($create_date == 0) ? '<unknown>' : strftime("%y/%m/%d %H:%M", $user_time);
			if($comment_uid > 0){
				if(!in_array($comment_uid, $this->usersCache)){
					$this->usersCache[$comment_uid] = $this->userHander->get($comment_uid);
					if ($this->usersCache[$comment_uid])
						$comments[$i]['name'] = $this->getUname($comment_uid);
						//$comments[$i]['name'] = $this->usersCache[$comment_uid]->uname();
				}
				if($xoopsUser){
					if ( $comments[$i]['uid'] == $xoopsUser->uid() || $admin )
						$comments[$i]['comment_edit'] = true;
				}
			}else{
				$comments[$i]['name'] = $comment_name.'@'._MD_POPNUPBLOG_FORM_GUEST;
				if ( $admin ) $comments[$i]['comment_edit'] = true;
			}
			$comments[$i]['comment'] = $post_text;
			$comments[$i]['vote'] = $vote;
			$i++;
		}
		return $comments;
	}
	
	function updateBlog($dates, $text, $title = '', $blogid='' ){
		global $xoopsUser, $HTTP_POST_VARS;

		$sqlDate = $dates['year'].'-'.$dates['month'].'-'.$dates['date'].' '.$dates['hours'].':'.$dates['minutes'].':'.$dates['seconds'];
		$title = htmlspecialchars($title);
		$sqlText = PopnupBlogUtils::convert2sqlString($text);
		$sqlTitle = PopnupBlogUtils::convert2sqlString($title);

		if ( empty($uid) || !$xoopsUser->isAdmin() ){
			$uid = $xoopsUser->uid();
		}
		if(empty($text)){
			$sql = sprintf("delete from %s where blogid=%u and blog_date='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $sqlDate);
		}else{
			$sql = sprintf("select blogid from %s where blogid = %u and blog_date = '%s'",POPNUPBLOG_TABLE_BLOG, $blogid, $sqlDate);
			if(!$result_select = $this->xoopsDB->query($sql)){
				return false;
			}
			if($this->xoopsDB->getRowsNum($result_select) == 0){
				$sql = sprintf("insert into %s(uid, blogid, blog_date, title, post_text) values(%u, %u, '%s', '%s', '%s')", POPNUPBLOG_TABLE_BLOG, $uid, $blogid, $sqlDate, $sqlTitle, $sqlText);
			}else{
				$sql = sprintf("update %s set title = '%s', post_text = '%s' where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $sqlTitle, $sqlText, $blogid, $sqlDate);
			}
		}
		//$last_text = $sqlTitle."\r\n<hr>".$sqlText;
		//$last_text = ereg_replace("\r\n[\t ]+", " ",$sqlTitle." : ".$sqlText);
		//$last_text = PopnupBlogUtils::_strcut($last_text,0,200);

		PopnupBlogUtils::log($sql);
		$this->xoopsDB->queryF($sql);
		$this->update_info($blogid);
		$blogurl = PopnupBlogUtils::createUrl($blogid , $dates['year'], $dates['month'], $dates['date'], $dates['hours'], $dates['minutes'], $dates['seconds'] );
		if(!empty($text) && $this->isPublic()){
			if($this->useUpdatePing()){
				PopnupBlogUtils::weblogUpdatesPing(
					PopnupBlogUtils::createRssURL($uid), 
					PopnupBlogUtils::createUrl($uid), 
					$this->getTitle(), 
					$title);
			}
			if( (array_key_exists('trackback', $HTTP_POST_VARS)) && 
				(!empty( $HTTP_POST_VARS['trackback'] ))
			){
				$tb_text = $this->ts->makeTareaData4Show($sqlText);
				$tb_text = PopnupBlogUtils::_strcut($tb_text,0,255);
				PopnupBlogUtils::send_trackback_ping(
					trim($HTTP_POST_VARS['trackback']), 
					$blogurl,
					$title,
					$this->getTitle(),
					$tb_text);
			}
		}
		if(!empty($text)){
			$show_name = PopnupBlogUtils::getXoopsModuleConfig('show_name');
			if ( $show_name==1 && (trim(PopnupBlogUtils::username($uid))!='') ){
				$uname = PopnupBlogUtils::username($uid);
			}else{
				$uname = $xoopsUser->uname();
			}
			PopnupBlogUtils::send_mailalias($blogid,$xoopsUser->getVar('email'),$uname,$title,$this->title,$blogurl,$text);
		}
		return true;
	}
	function update_info($blogid){
//		if (empty($sqlTitle)){
//			$sql = sprintf("update %s set last_update = CURRENT_TIMESTAMP() where uid = %u",
//			POPNUPBLOG_TABLE_INFO, $uid );
//		} else {
			$sql = sprintf("update %s set last_update = CURRENT_TIMESTAMP() where blogid = %u",
				POPNUPBLOG_TABLE_INFO,$blogid );
//		}
		$this->xoopsDB->queryF($sql);
	}
	function send_comment($mailto,$title,$sqlname,$message,$uname){
		global $xoopsConfig;

		if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$mailto)) { 
			return false;
		}
		$mailcode = get_mailcode::get_mailcode();
		$subject = "[".$xoopsConfig['sitename']."] PopnupBLOG: ".$title;
		if (function_exists('mb_encode_mimeheader')){
			$subject = mb_encode_mimeheader($subject, $mailcode, "B");
		}
		$message = $sqlname.": ".$message."\n\n-----------\n\n".
			vsprintf(_MD_POPNUPBLOG_HELLO,$uname)."\n\n".
			_MD_POPNUPBLOG_GETCOMMENT."\n";
		$message = PopnupBlogUtils::convert_encoding($message,"auto", $mailcode);
		$chgheader = 
			"From: ". $xoopsConfig['adminmail'] ."\n" . 
			"Reply-To: ". $mailto . "\n" . 
			"Mime-Version: 1.0\n" . 
			"Content-Type: text/plain; charset=". $mailcode."\n";
			"Content-Transfer-Encoding: 7bit\n";
//		if (function_exists('mb_send_mail'))
//			mb_send_mail($mailto,$subject,$message,$chgheader);
//		else
			mail($mailto,$subject,$message,$chgheader);
	}
	function insertComment($dates, $name, $comment,$vote){
		global $xoopsUser;
		$uid = 0;
		if($xoopsUser){
			$uid = $xoopsUser->uid();
			$userTZ = $xoopsUser->getVar("timezone_offset");
		} else { 
			$userTZ = $xoopsConfig['default_TZ'];
		}
		$user_time = strtotime($dates['year'].'-'.$dates['month'].'-'.$dates['date'].' '.$dates['hours'].':'.$dates['minutes'].':'.$dates['seconds']);
		$server_time = userTimeToServerTime($user_time,$userTZ);
		$year    = strftime("%Y", $server_time);
		$month   = strftime("%m", $server_time);
		$date    = strftime("%d", $server_time);
		$hours   = strftime("%H", $server_time);
		$minutes = strftime("%M", $server_time);
		$seconds = strftime("%S", $server_time);
		$sqlDate = $year.'-'.$month.'-'.$date.' '.$hours.':'.$minutes.':'.$seconds;
		$sqlName = PopnupBlogUtils::convert2sqlString($name);
		$comment = htmlspecialchars($comment);
		$sqlComment = PopnupBlogUtils::convert2sqlString($comment); 
		// Check Duplicate vote

		if($vote!=0 && $dbResult = $this->xoopsDB->query('select count(*) from '.POPNUPBLOG_TABLE_COMMENT.' where blogid = '.$this->blogid.' and blog_date = '.$this->xoopsDB->quoteString($sqlDate).' and vote<>0')){ 
			list($cnt) = $this->xoopsDB->fetchRow($dbResult);
			if ($cnt>0) return false;
		}
		$sql = sprintf("select title from %s where blogid = %u and blog_date = '%s'",POPNUPBLOG_TABLE_BLOG, $this->blogid, $sqlDate);
		if(!$result_select = $this->xoopsDB->query($sql)){
			return false;
		}
		list($title) = $this->xoopsDB->fetchRow($result_select);
//		if($this->xoopsDB->getRowsNum($counts) == 1){
		$sql_base = "insert into %s (blogid, blog_date, comment_id, comment_uid, comment_name, post_text, create_date, vote) values(%u, '%s', null, %u, '%s', '%s', '%s', %d)";
		$sql = sprintf($sql_base, POPNUPBLOG_TABLE_COMMENT, $this->blogid, $sqlDate, $uid, $sqlName, $sqlComment, date("Y-m-d H:i:s",time()), $vote);
		$result = $this->xoopsDB->queryF($sql);
		if ($vote==1){
			$sql = sprintf("update %s set votes_yes = votes_yes + 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $this->blogid, $sqlDate);
			$result = $this->xoopsDB->queryF($sql);
		}elseif ($vote==-1){
			$sql = sprintf("update %s set votes_no = votes_no + 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $this->blogid, $sqlDate);
			$result = $this->xoopsDB->queryF($sql);
		}
		$mailto = PopnupBlogUtils::get_email_from_blogid($this->blogid);
		if (!empty($mailto) && !empty($sqlComment)) {
			$this->send_comment($mailto,$title,$sqlName,$sqlComment, $xoopsUser->uname());
		}
		return true;
//		}
//		return false;
	}
	function escapeHtml($text){
		$result = $text;
		// $result = ereg_replace('&', '&amp;', $text);
		$result = ereg_replace('<', '&lt;', $result);
		$result = ereg_replace('>', '&gt;', $result);
		// $result = ereg_replace('\'', '&apos;', $result);
		$result = ereg_replace('"', '&quot;', $result);
		//$result = ereg_replace('\r\n', '\n', $result);
		//$result = ereg_replace('\r', '\n', $result);
		//$result = ereg_replace('\n', '<br />', $result);
		return $result;
	}
	
	function getBlogIndex(){
		global $xoopsUser;
		$sql = 'select distinct DATE_FORMAT(blog_date, \'%Y\') year, DATE_FORMAT(blog_date, \'%m\') month from '.POPNUPBLOG_TABLE_BLOG.' where blogid = '.$this->blogid.' and blog_date != \'0000-00-00\' order by year desc, month';
		if(!$result_select = $this->xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		while(list($year, $month) = $this->xoopsDB->fetchRow($result_select)){
			// $result[$year][$month] = $month;
			$result[$year][$month]['month'] = $month;
			$result[$year][$month]['url'] = PopnupBlogUtils::createUrl($this->blogid, $year, $month);
		}
		return $result;
	}
	

	function recieve_trackback_ping($dates = null){
		global $HTTP_POST_VARS, $HTTP_GET_VARS;
		$referer = null;
		$title = null;
		$tb = $this->useTrackBack();
		if(($tb == true) && array_key_exists('url', $HTTP_POST_VARS) && !empty($HTTP_POST_VARS['url'])){
				$referer = trim($HTTP_POST_VARS['url']);
				$title = array_key_exists('title', $HTTP_POST_VARS) ? PopnupBlogUtils::convert_encoding(trim($HTTP_POST_VARS['title']),'auto', _CHARSET) : null;
		}elseif(($tb == true) && array_key_exists('url', $HTTP_GET_VARS) && !empty($HTTP_GET_VARS['url'])){
			$referer = trim($HTTP_GET_VARS['url']);
			$title = array_key_exists('blog_name', $HTTP_GET_VARS) ? PopnupBlogUtils::convert_encoding(trim($HTTP_GET_VARS['blog_name']),'auto', _CHARSET).'&nbsp;/&nbsp;' : null;
			$title .= array_key_exists('title', $HTTP_GET_VARS) ? PopnupBlogUtils::convert_encoding(trim($HTTP_GET_VARS['title']),'auto', _CHARSET) : null;
		}elseif(array_key_exists('HTTP_REFERER', $_SERVER)){
			$referer = trim($_SERVER['HTTP_REFERER']);
			if( (empty($referer)) || (preg_match('/^'.ereg_replace('/', '\\/', XOOPS_URL).'*/', $referer)) ){
				return "same site";
			}
		}else{
			return "no args";
		}
		
		
		if(PopnupBlogUtils::isCompleteDate($dates)){
			$targetDate = $dates['year'].'-'.$dates['month'].'-'.$dates['date'].' '.$dates['hours'].':'.$dates['minutes'].':'.$dates['seconds'];
		}
		
		// get current date
		$sql = 'select blog_date from '.POPNUPBLOG_TABLE_BLOG.' where blogid = '.$this->blogid.' order by blog_date desc limit 1';
		if(!$result_select = $this->xoopsDB->query($sql)){
			return "sql error";
		}
		list($current_date) = $this->xoopsDB->fetchRow($result_select);
		
		if(!empty($current_date)){
			$this->incrementTrackBack($current_date, $referer, $title);
			if( (!empty($targetDate)) && ($current_date != $targetDate)){
				$this->incrementTrackBack($targetDate, $referer, $title);
			}
		}
		return "ok";
	}
	function incrementTrackBack($date, $url, $title){
		$t = empty($title) ? 'null' : $this->xoopsDB->quoteString($title);
		$u = $this->xoopsDB->quoteString($url);
		$d = $this->xoopsDB->quoteString($date);
		$update = "update ".POPNUPBLOG_TABLE_TRACKBACK." set count = count+1, title = %s where blogid = %u and t_date = %s and url = %s";
		$this->xoopsDB->queryF(sprintf($update,  $t, $this->blogid, $d, $u));
		if($this->xoopsDB->getAffectedRows() == 0){
			$insert = "insert into ".POPNUPBLOG_TABLE_TRACKBACK."(blogid, t_date, count, title, url) VALUES(%u, %s, 1, %s, %s)";
			$this->xoopsDB->queryF(sprintf($insert, $this->blogid, $d, $t, $u));
		}
	}
	
	function getTrackBack($date){
		global $tb_by_serchengine,$hide_referer;
		if ($hide_referer==1) return;
		$sqlDate = $this->xoopsDB->quoteString($date['year']."-".$date['month']."-".$date['date'].' '.$date['hours'].':'.$date['minutes'].':'.$date['seconds']);
		$sql = 'select count, t_date, title, url from '.POPNUPBLOG_TABLE_TRACKBACK.' where blogid = '.$this->blogid.' and t_date = '.$sqlDate.'  order by count desc';
		if(!$result_select = $this->xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		while(list($count, $date, $title, $url) = $this->xoopsDB->fetchRow($result_select)){
			$t = array();
			$t['count'] = $count;
			$t['date'] = $date;
			$t['url'] = htmlspecialchars($url);
			if( preg_match('/http:\/\/\w+\.(\w+).*('.$tb_by_serchengine.')=([^&]+)/',$t['url'],$m)){
				if ( function_exists('mb_convert_encoding') ){
					$t['title'] = 'Search ' . $m[1] . ' : ' . mb_convert_encoding(urldecode($m[3]),_CHARSET,'auto');
				}else{
					$t['title'] = 'Search ' . $m[1] . ' : ' . urldecode($m[3]);
				}
			}else{
				if (function_exists('mb_convert_encoding') ){
					$t['title'] = htmlspecialchars( mb_convert_encoding( empty($title) ? $url : '<b>[TrackBack]'.$title.'</b>') );
				}else{
					$t['title'] = htmlspecialchars( empty($title) ? $url : '<b>[TrackBack]'.$title.'</b>' );
				}
			}
			$result[] = $t;
		}
		return $result;
	}
	
	// deprecated method 
	function getApplicationNum(){
		global $xoopsDB;
		if(!$dbResult = $xoopsDB->query('select count(*) num from '.POPNUPBLOG_TABLE_APPL)){
			return 0;
		}
		if(list($num) = $xoopsDB->fetchRow($dbResult)){
			return $num;
		}
		return 0;
	}

	function getEmailByUid( $uid ){
		$poster = new XoopsUser( $uid ) ;
		// check if invalid uid
		if( $poster->uname() == '' ) return '' ;
		return $poster->email();
	}
	function getUname( $uid ){
		$show_name = PopnupBlogUtils::getXoopsModuleConfig('show_name');
		if ( $show_name==1 && (trim(PopnupBlogUtils::username($uid))!='') )
			return PopnupBlogUtils::username($uid);
		else
			return PopnupBlogUtils::uname($uid);
	}
}
?>
